/**
 * 文件下载
 * @author xiaoxujs
 */

import axios from "axios";

//模板下载
/**
 *
 * @param url 下载地址
 * @param value 参数
 * @param fileExtension 后缀名
 * @param responseType 接收类型
 */
interface IValue {
  [value: string]: string;
}
export const gethandleTemplateDownload = async (
  url: string,
  value: IValue,
  fileExtension: string,
  responseType: "arraybuffer" | "blob"
) => {
  const token: string = sessionStorage.getItem("token") as string;
  let newValue = "?";
  for (const key in value) {
    newValue += key + "=" + value[key] + "&";
  }
  newValue = newValue.substring(0, newValue.length - 1);
  axios({
    method: "get",
    url: url + newValue,
    //重要：相应类型必须为blob
    responseType: responseType,
    headers: {
      token: token,
    },
  }).then((res) => {
    let contentDisposition = decodeURI(res.headers["content-disposition"]);
    let fileRegex = new RegExp(
      "([^(filename=)]+\\." + fileExtension + "?)$",
      "g"
    );

    let result = contentDisposition.match(fileRegex)![0];

    var link = document.createElement("a");
    //将文件流信息传入
    link.href = window.URL.createObjectURL(new Blob([res.data]));
    link.download = result;
    link.click();
    window.URL.revokeObjectURL(link.href);
  });
};
// post 导出
export const postHandleTemplateDownload = async (
  url: string,
  value: IValue,
  fileExtension: string,
  responseType: "arraybuffer" | "blob"
) => {
  const token: string = sessionStorage.getItem("token") as string;
  //发起请求
  axios({
    method: "post",
    url: url,
    data: value,
    //重要：相应类型必须为blob
    responseType: responseType,
    headers: {
      token: token,
    },
  }).then((res) => {
    let fileRegex = new RegExp(
      "([^(filename=)]+\\." + fileExtension + "?)$",
      "g"
    );
    var link = document.createElement("a");//创建一个a标签
    //将文件流信息传入
    link.href = window.URL.createObjectURL(new Blob([res.data]));
    console.log(res)
    link.download = decodeURI(res.headers["content-disposition"]).match(fileRegex)![0];
    link.click(); //模拟点击a标签
    window.URL.revokeObjectURL(link.href);
  });
}
